<template>
  <div class="payment-page">
    <!-- 页面头部 -->
    <header class="payment-header">
      <button class="back-btn" @click="handleGoBack">← 返回订单</button>
      <h1 class="page-title">确认支付</h1>
    </header>

    <!-- 加载状态 -->
    <div v-if="isLoading" class="cart-loading">
      <div class="loading-spinner"></div>
      <p>加载订单数据中...</p>
    </div>

    <!-- 主体内容 -->
    <main class="payment-content" v-else>
      <!-- 订单数据异常提示 -->
      <div class="order-error" v-if="orderError">
        <el-icon class="error-icon"><WarningFilled /></el-icon>
        <p class="error-text">{{ orderError }}</p>
        <button class="go-cart-btn" @click="goToCart">返回购物车</button>
      </div>

      <!-- 正常订单内容 -->
      <div v-else>
        <!-- 地址管理模块（实体商品显示） -->
        <div class="address-card" @click="handleSelectAddress" >
          <div class="card-header">
            <span class="card-title">收货地址</span>
            <span class="edit-icon">
              <el-icon :size="16"><Edit /></el-icon>
            </span>
          </div>
          <div class="address-content" v-if="selectedAddress">
            <div class="recipient-info">
              <span class="recipient-name">{{ selectedAddress.receiver }}</span>
              <span class="recipient-phone">{{ formatPhone(selectedAddress.phone) }}</span>
            </div>
            <div class="address-detail">
              {{ selectedAddress.address }}
            </div>
          </div>
          <div class="address-placeholder" v-else>
            <el-icon :size="24" class="add-icon"><Plus /></el-icon>
            <span class="add-text">添加收货地址</span>
          </div>
        </div>

        <!-- 2. 支付方式模块（ID改为数字0/1/2，适配后端枚举） -->
        <div class="payment-method-card">
          <div class="card-header">
            <span class="card-title">支付方式</span>
          </div>
          <div class="method-list">
            <div
                class="method-item"
                v-for="method in paymentMethods"
                :key="method.id"
                @click="selectedMethodId = method.id"
            >
              <div class="method-icon">
                <img :src="method.icon" alt="支付方式图标" class="icon-img">
              </div>
              <div class="method-name">{{ method.name }}</div>
              <div class="method-desc">{{ method.desc }}</div>
              <div class="method-selector">
                <el-radio v-model="selectedMethodId" :label="method.id" border />
              </div>
            </div>
          </div>
        </div>

        <!-- 3. 订单明细模块（同步购物车选中商品） -->
        <div class="order-detail-card">
          <div class="card-header">
            <span class="card-title">订单明细</span>
            <span class="item-total">共 {{ orderGoods.length }} 件商品</span>
          </div>
          <div class="detail-list">
            <div class="detail-item" v-for="item in orderGoods" :key="item.prod_id">
              <div class="item-img">
                <img :src="item.image_url" alt="商品图片" class="goods-img" @error="handleImgError($event)">
              </div>
              <div class="item-info">
                <div class="item-name">{{ item.prod_name }}</div>
                <div class="item-price-row">
                  <span class="item-unit-price">¥{{ item.prod_price.toFixed(2) }}</span>
                  <span class="item-subtotal">小计：¥{{ (item.prod_price * item.count).toFixed(2) }}</span>
                </div>
              </div>
              <div class="item-quantity">×{{ item.count }}</div>
            </div>
          </div>
          <!-- 金额明细（修复空值，基于购物车商品计算） -->
          <div class="order-total">
            <div class="total-item">
              <span class="total-label">商品总价</span>
              <span class="total-value">¥{{ goodsTotal.toFixed(2) }}</span>
            </div>

            <!-- 实付金额 -->
            <div class="total-item final-total">
              <span class="total-label">实付款</span>
              <span class="total-value">¥{{ finalTotal.toFixed(2) }}</span>
            </div>
          </div>
        </div>

      </div>
    </main>

    <!-- 底部支付栏（修复金额显示） -->
    <footer class="payment-footer" v-if="!isLoading && !orderError">
      <div class="footer-left">
        <div class="footer-total">
          <span class="total-text">实付款：</span>
          <span class="total-amount">¥{{ finalTotal.toFixed(2) }}</span>
        </div>
      </div>
      <button
          class="pay-btn"
          @click="handleSubmitPayment"
          :disabled="(!selectedAddress) || isSubmitting"
      >
        <span v-if="!isSubmitting">确认支付 ¥{{ finalTotal.toFixed(2) }}</span>
        <el-loading-spinner v-else class="pay-loading" />
      </button>
    </footer>

    <!-- 地址选择弹窗 -->
    <el-dialog
        title="选择收货地址"
        v-model="showAddressDialog"
        width="90%"
        max-width="500px"
        destroy-on-close
    >
      <div class="address-list">
        <div
            class="dialog-address-item"
            v-for="(addr, index) in addressList"
            :key="index"
            @click="selectAddress(index)"
        >
          <div class="addr-recipient">
            <span class="addr-name">{{ addr.receiver }}</span>
            <span class="addr-phone">{{ formatPhone(addr.phone) }}</span>
            <el-tag v-if="addr.is_default" size="small" type="primary">默认</el-tag>
          </div>
          <div class="addr-detail">{{ addr.address }}</div>
          <div class="addr-actions">
            <button class="addr-edit" @click.stop="handleEditAddress(index)">编辑</button>
            <button class="addr-delete" @click.stop="handleDeleteAddress(index)">删除</button>
          </div>
        </div>
        <button class="add-address-btn" @click="handleAddAddress">
          <el-icon><Plus /></el-icon>
          新增收货地址
        </button>
      </div>
    </el-dialog>

    <!-- 新增/编辑地址弹窗 -->
    <el-dialog
        :title="editAddressIndex === -1 ? '新增收货地址' : '编辑收货地址'"
        v-model="showEditAddressDialog"
        width="90%"
        max-width="500px"
        destroy-on-close
    >
      <el-form :model="formAddress" ref="addressFormRef" label-width="80px" class="address-form" :rules="addressRules">
        <el-form-item label="收货人" prop="receiver">
          <el-input v-model="formAddress.receiver" placeholder="请输入收货人姓名" :disabled="isSubmitting"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="formAddress.phone" placeholder="请输入手机号" :disabled="isSubmitting" maxlength="11"></el-input>
        </el-form-item>
        <el-form-item label="详细地址" prop="address">
          <el-input v-model="formAddress.address" placeholder="请输入地区、街道、门牌号等详细地址" :disabled="isSubmitting"></el-input>
        </el-form-item>
        <el-form-item>
          <el-checkbox v-model="formAddress.is_default" :disabled="isSubmitting">设为默认地址</el-checkbox>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showEditAddressDialog = false" :disabled="isSubmitting">取消</el-button>
        <el-button type="primary" @click="saveAddress" :disabled="isSubmitting">保存</el-button>
      </template>
    </el-dialog>


    <!-- 支付确认弹窗（核心：展示订单编号、创建时间、支付状态、商品ID和数量） -->
    <!-- 支付确认弹窗（核心修改：新增地址信息+完善商品明细） -->
    <el-dialog
        title="支付确认"
        v-model="showPayConfirmDialog"
        width="90%"
        max-width="500px"
        destroy-on-close
        :before-close="handleDialogClose"
    >
      <div class="pay-confirm-content">
        <!-- 1. 新增：收货地址信息 -->
        <div class="confirm-item">
          <span class="confirm-label">收货地址：</span>
          <div class="confirm-value address-detail">
            <div class="address-receiver">
              {{ selectedAddress.receiver }} {{ formatPhone(selectedAddress.phone) }}
            </div>
            <div class="address-content">{{ selectedAddress.address }}</div>
          </div>
        </div>

        <!-- 2. 订单号（原有） -->
        <div class="confirm-item">
          <span class="confirm-label">订单编号：</span>
          <span class="confirm-value">{{ payConfirmData.order_no }}</span>
          <button
              class="copy-btn"
              @click="copyOrderNo"
              :disabled="!payConfirmData.order_no"
          >
            <el-icon :size="14"></el-icon> 复制
          </button>
        </div>

        <!-- 3. 订单创建时间（原有） -->
        <div class="confirm-item">
          <span class="confirm-label">创建时间：</span>
          <span class="confirm-value">{{ formatDateTime(payConfirmData.create_time) || formatDateTime(Date.now()) }}</span>
        </div>

        <!-- 4. 支付方式（原有） -->
        <div class="confirm-item">
          <span class="confirm-label">支付方式：</span>
          <span class="confirm-value">
        {{ paymentMethods.find(item => item.id === selectedMethodId)?.name || '未选择' }}
      </span>
        </div>

        <!-- 5. 商品明细（修改：展示商品名称+数量+ID） -->
        <div class="confirm-item product-details">
          <span class="confirm-label">商品明细：</span>
          <div class="product-list">
            <div class="product-item" v-for="item in orderGoods" :key="item.prod_id">
          <span class="product-info">
            <!-- 新增商品名称，突出显示 -->
            <strong>{{ item.prod_name }}</strong>
            | 数量：<span style="color: #ff5722;">{{ item.count }}</span>
            | ID：{{ item.prod_id }}
          </span>
            </div>
          </div>
        </div>

        <!-- 6. 总金额（原有） -->
        <div class="confirm-item">
          <span class="confirm-label">实付金额：</span>
          <span class="confirm-value amount">¥{{ finalTotal.toFixed(2) }}</span>
        </div>

        <!-- 7. 订单状态（原有） -->
        <div class="confirm-item">
          <span class="confirm-label">订单状态：</span>
          <span class="confirm-value">
        <el-tag :type="getStatusTagType(payConfirmData.status)">
          {{ getStatusText(payConfirmData.status) }}
        </el-tag>
      </span>
        </div>
      </div>

      <!-- 弹窗底部按钮（修改：点击“去支付”触发二次确认） -->
      <template #footer>
        <el-button @click="showPayConfirmDialog = false" :disabled="isSubmitting">取消</el-button>
        <el-button
            type="primary"
            @click="handlePayConfirm"
        :disabled="isSubmitting || !payConfirmData.order_no"
        >
        <span v-if="!isSubmitting">去支付</span>
        <el-loading-spinner v-else class="pay-loading" />
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, reactive } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import ProductApi from "@/api/Product.js";
import {
  ElMessage, ElRadio, ElTag, ElIcon, ElInput, ElButton,
  ElForm, ElFormItem, ElCheckbox, ElMessageBox
} from 'element-plus';
import {
  Edit, InfoFilled, WarningFilled,  Plus,
} from '@element-plus/icons-vue';
import defaultImage from '@/assets/图片加载失败.png';
import WeChatImage from '@/assets/微信支付.png'
import PayBabyImage from '@/assets/支付宝支付.png'
import CardImage from '@/assets/银行卡支付.png'
import AddressApi from '@/api/address.js'
// 引入订单API
import OrderApi from '@/api/order.js';

// 路由实例
const router = useRouter();
const route = useRoute();

// 状态管理：加载、错误、提交中
const isLoading = ref(true);
const orderError = ref('');
const isSubmitting = ref(false);

// 1. 从购物车同步选中商品（核心：解析路由传递的cartData）
const orderGoods = ref([]);

// 2. 地址管理相关
const addressList = ref([]);
// 默认选中地址
const selectedAddress = ref(null);
// 地址弹窗状态
const showAddressDialog = ref(false);
const showEditAddressDialog = ref(false);
const editAddressIndex = ref(-1);

// 地址表单数据
const formAddress = reactive({
  id: null,
  receiver: '',
  phone: '',
  address: '',
  is_default: 0
});
// 地址表单引用
const addressFormRef = ref(null);
// 地址表单验证规则
const addressRules = ref({
  receiver: [
    { required: true, message: '请输入收货人姓名', trigger: 'blur' },
    { max: 20, message: '收货人姓名不能超过20个字符', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的11位手机号', trigger: 'blur' }
  ],
  address: [
    { required: true, message: '请输入详细地址', trigger: 'blur' },
    { max: 100, message: '详细地址不能超过100个字符', trigger: 'blur' }
  ]
});

// 3. 支付方式（ID改为数字0/1/2，适配后端枚举：0-支付宝/1-微信/2-银行卡）
const paymentMethods = ref([
  {
    id: 0, // 支付宝：对应后端pay_type=0
    name: '支付宝支付',
    desc: '推荐使用，支持花呗分期',
    icon: PayBabyImage
  },
  {
    id: 1, // 微信：对应后端pay_type=1
    name: '微信支付',
    desc: '微信扫码支付，支持零钱通',
    icon: WeChatImage
  },
  {
    id: 2, // 银行卡：对应后端pay_type=2
    name: '银行卡支付',
    desc: '支持储蓄卡/信用卡，免手续费',
    icon: CardImage
  }
]);
const selectedMethodId = ref(0); // 默认选中支付宝（ID=0）

// 4. 金额相关（基于购物车商品计算）

// 计算属性：商品总价（从购物车商品计算）
const goodsTotal = computed(() => {
  return orderGoods.value.reduce((sum, item) => {
    // 步骤1：强制转换 prod_price 和 count 为数字
    const price = Number(item.prod_price);
    const quantity = Number(item.count);

    // 步骤2：校验是否为有效数字，无效则跳过（避免 sum 变成 NaN）
    if (isNaN(price) || isNaN(quantity) || price < 0 || quantity < 0) {
      return sum; // 无效数据不参与求和
    }

    // 步骤3：有效数字才累加
    return sum + (price * quantity);
  }, 0); // 初始值为 0（确保 sum 初始是数字）
});


// 计算属性：实付金额（商品总价 - 优惠）
const finalTotal = computed(() => {
  return goodsTotal.value;
});




// 支付确认弹窗状态（字段名与后端对齐，status为数字）
const showPayConfirmDialog = ref(false);
const payConfirmData = ref({
  order_no: '', // 与后端字段对齐（下划线命名）
  create_time: '', // 与后端字段对齐
  status: 0, // 后端订单状态：0-待支付/1-已支付/2-已发货/3-已完成
  pay_type: 0, // 后端支付方式：0-支付宝/1-微信/2-银行卡
  total_amount: 0, // 与后端字段对齐
  list: [
    {
      prod_name: '',
      count: 0,
    }
  ],
});

// 生命周期：初始化（核心：从路由获取购物车选中商品）
onMounted(async () => {
  try {
    // 1. 解析路由传递的购物车选中商品数据（从购物车页面跳转时携带）
    const cartDataStr = route.query.cartData;
    if (!cartDataStr) {
      throw new Error('未获取到购物车商品数据，请从购物车页面进入');
    }

    // 2. 解析JSON数据（处理可能的解析错误）
    const cartData = JSON.parse(decodeURIComponent(cartDataStr));
    if (!Array.isArray(cartData) || cartData.length === 0) {
      throw new Error('购物车选中商品为空，请选择商品后再结算');
    }

    // 3. 同步购物车商品到订单明细（补充必要字段）
    orderGoods.value = cartData.map(item => ({
      ...item,
      prod_id: item.prod_id || `PROD${Date.now()}${Math.floor(Math.random() * 100)}`,
      prod_name: item.prod_name || '未知商品',
      image_url: item.image_url || defaultImage,
      prod_price: Number(item.prod_price) || 0,
      count: Number(item.count) || 1,
    }));

    // 整改后的地址获取逻辑
    addressList.value = await AddressApi.list();
    // 获取默认地址或第一个地址作为选中地址
    selectedAddress.value = addressList.value.find(addr => addr.is_default === 1)
        || addressList.value[0]
        || null;
  } finally {
    // 结束加载状态
    isLoading.value = false;
    // 启动倒计时（仅当订单正常加载时）
  }
});


// ---------------------- 地址管理方法 ----------------------
// 选择地址
const handleSelectAddress = () => {
  if (!isSubmitting.value) {
    showAddressDialog.value = true;
  }
};

// 选中地址并关闭弹窗
const selectAddress = (index) => {
  if (!isSubmitting.value) {
    selectedAddress.value = addressList.value[index];
    showAddressDialog.value = false;
  }
};

// 新增地址
const handleAddAddress = async () => {
  if (isSubmitting.value) return;
  await  AddressApi.list();
  // 重置表单
  Object.assign(formAddress, {
    id: null,
    receiver: '',
    phone: '',
    address: '',
    is_default: 0
  });
  editAddressIndex.value = -1;
  showEditAddressDialog.value = true;
  showAddressDialog.value = false;
};

// 编辑地址
const handleEditAddress = async (index) => {
  if (isSubmitting.value) return;
  const addr = addressList.value[index];
  Object.assign(formAddress, addr);
  editAddressIndex.value = index;
  showEditAddressDialog.value = true;
  await AddressApi.list();
};

// 删除地址 - 整改后的逻辑
const handleDeleteAddress = async (index) => {
  if (isSubmitting.value) return;
  const addr = addressList.value[index];

  // 禁止删除默认地址
  if (addr.is_default === 1) {
    ElMessage.warning('默认地址不能删除，请先设置其他地址为默认');
    return;
  }

  try {
    isSubmitting.value = true;
    // 调用API删除地址
    const result = await AddressApi.delete(addr.id);
    if (result) {
      // 若删除的是当前选中地址，切换到新默认地址
      const isSelected = selectedAddress.value && selectedAddress.value.id === addr.id;
      addressList.value.splice(index, 1);
      ElMessage.success('地址已成功删除');

      // 切换选中地址
      if (isSelected) {
        const newDefault = addressList.value.find(item => item.is_default === 1);
        selectedAddress.value = newDefault || addressList.value[0] || null;
      }
    }
  }  finally {
    await AddressApi.list();
    isSubmitting.value = false;
  }
};

// 保存地址（新增/编辑）- 整改后的逻辑
const saveAddress = async () => {
  if (isSubmitting.value || !addressFormRef.value) return;

  try {
    // 1. 表单验证
    await addressFormRef.value.validate();
    isSubmitting.value = true;

    // 2. 关键：将 ElCheckbox 的布尔值 true/false 转为数值 1/0
    const submitIsDefault = formAddress.is_default ? 1 : 0;
    // 构造最终提交给后端的地址数据（包含转换后的 is_default）
    const submitAddress = {
      ...formAddress,
      is_default: submitIsDefault
    };

    // 3. 处理默认地址逻辑：若设为默认（1），其他地址设为非默认（0）
    if (submitIsDefault === 1) {
      // 更新前端列表中的其他地址为非默认
      addressList.value.forEach(item => {
        if (item.id !== submitAddress.id) {
          item.is_default = 0;
        }
      });
    }

    // 4. 新增地址
    if (editAddressIndex.value === -1) {
      const result = await AddressApi.add(submitAddress);
      if (result && result.id) {
        submitAddress.id = result.id;
        addressList.value.push(submitAddress);
        ElMessage.success('地址添加成功');
      }
    }
    // 5. 编辑地址
    else {
      const result = await AddressApi.edit(submitAddress);
      if (result) {
        addressList.value.splice(editAddressIndex.value, 1, submitAddress);
        ElMessage.success('地址修改成功');
      }
    }

    // 6. 若为默认地址（1），更新当前选中地址
    if (submitIsDefault === 1) {
      selectedAddress.value = submitAddress;
    }

    // 7. 关闭弹窗
    showEditAddressDialog.value = false;
  } catch (error) {
    ElMessage.error(error.message || '操作失败，请重试');
  } finally {
    isSubmitting.value = false;
  }
};


// ---------------------- 工具方法 ----------------------
// 手机号格式化（中间4位打星）
const formatPhone = (phone) => {
  if (!phone || phone.length !== 11) return phone;
  return phone.replace(/(\d{3})(\d{4})(\d{4})/, '$1****$3');
};

// 时间格式转换
const formatDateTime = (time) => {
  if (!time) return '暂无数据';

  let date;
  // 处理时间戳（毫秒/秒级）
  if (typeof time === 'number') {
    // 若为10位时间戳（秒），转为13位（毫秒）
    date = new Date(time.toString().length === 10 ? time * 1000 : time);
  }
  // 处理ISO字符串
  else if (typeof time === 'string') {
    date = new Date(time);
  } else {
    return '格式错误';
  }

  // 补零工具
  const padZero = (num) => num.toString().padStart(2, '0');

  const year = date.getFullYear();
  const month = padZero(date.getMonth() + 1);
  const day = padZero(date.getDate());
  const hours = padZero(date.getHours());
  const minutes = padZero(date.getMinutes());
  const seconds = padZero(date.getSeconds());

  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
};

// 商品图片加载失败处理
const handleImgError = (e) => {
  e.target.src = defaultImage;
};

// 复制订单号
const copyOrderNo = () => {
  if (!payConfirmData.value.order_no) {
    ElMessage.warning('订单号为空，无法复制');
    return;
  }
  navigator.clipboard.writeText(payConfirmData.value.order_no)
      .then(() => {
        ElMessage.success('订单号已复制到剪贴板');
      })
      .catch(() => {
        ElMessage.error('复制失败，请手动复制');
      });
};


// 订单状态数字转文字（适配后端：0-待支付/1-已支付/2-已发货/3-已完成）
const getStatusText = (status) => {
  const statusMap = {
    0: '待支付',
    1: '已支付',
    2: '已发货',
    3: '已完成'
  };
  return statusMap[status] || '未知状态';
};

// 订单状态对应的Tag类型（控制颜色）
const getStatusTagType = (status) => {
  const typeMap = {
    0: 'warning', // 待支付-黄色
    1: 'success', // 已支付-绿色
    2: 'info',    // 已发货-蓝色
    3: 'primary'  // 已完成-深蓝色
  };
  return typeMap[status] || 'default';
};

// ---------------------- 导航与支付方法 ----------------------
// 返回上一页
const handleGoBack = () => {
  if (!isSubmitting.value) {
    router.go(-1);
  }
};

// 返回购物车
const goToCart = () => {
  router.push('/cart');
};
// ---------------------- 支付相关新增方法 ----------------------
const orderId=ref( null);
// 确认支付方法（传递数字pay_type给后端，新增商品ID和数量参数）
const handleSubmitPayment = async () => {
  // 1. 基础校验
  if (isSubmitting.value || !selectedAddress.value) return;

  try {
    isSubmitting.value = true;
    ElMessage.info('正在创建订单...');


    // 2. 构造订单创建参数（新增：商品ID和数量列表）
    const orderParams = {
      order: {
        // 仅传递后端需要的字段，避免冗余
        addr_id: selectedAddress.value?.id,  // 可选链操作：防止selectedAddress为null时报错
        pay_type: Number(selectedMethodId.value),  // 确保是数字类型（与后端int类型匹配）
        total_amount: Number(finalTotal.value.toFixed(2)),  // 保留2位小数，转为数字
        status: 0  // 固定为"待支付"状态，后端也可默认设置
      },
      products: orderGoods.value.map(item => ({
        prod_id: Number(item.prod_id),  // 确保商品ID是数字（与后端Integer类型匹配）
        prod_name: item.prod_name?.trim(),  // 去除首尾空格，避免脏数据
        prod_price: Number(item.prod_price.toFixed(2)),  // 单价保留2位小数
        count: Number(item.count)  // 确保数量是数字
      }))
    };

    // 3. 调用后端创建订单接口（传递包含商品ID和数量的参数）
    orderId.value= await OrderApi.createOrder(orderParams);
    console.log(orderId.value)

    const result= await OrderApi.getOrderById(orderId.value);

    // 4. 填充弹窗数据（订单号、时间、状态仅弹窗使用）
    payConfirmData.value = {
      order_no: result.order_no || '',          // 后端订单号
      create_time: result.create_time || Date.now(),    // 后端创建时间（无则用当前时间）
      status: result.status || 0,               // 后端订单状态（默认0-待支付）
      pay_type: result.pay_type || 0,  // 数字支付方式
      total_amount: result.total_amount || 0 ,    // 实付金额
      list: orderGoods.value.map(item => ({
        prod_id: item.prod_id,
        prod_name: item.prod_name,
        prod_price: item.prod_price,
        count: item.count
      }))
    };

    // 5. 打开支付确认弹窗（已添加商品ID和数量展示）
    showPayConfirmDialog.value = true;

  } finally {
    isSubmitting.value = false;
  }
};


// 二次确认支付（点击“去支付”触发）
const handlePayConfirm = () => {

  const totalAmount =payConfirmData.value.total_amount;


  // 3. 使用转换后的数字调用toFixed
  ElMessageBox.confirm(
      `您确定要支付 ¥${totalAmount.toFixed(2)} 吗？`, // 这里使用转换后的totalAmount
      '支付确认',
      {
        confirmButtonText: '确定支付', // 确认按钮文本
        cancelButtonText: '取消', // 取消按钮文本
        type: 'warning', // 弹窗类型（警告色）
        center: true // 按钮居中
      }
  )
      .then(async () => {
        // 用户点击“确定支付”，调用原支付方法
        ElMessage.success('支付成功')
        await OrderApi.updateSetPayTime(orderId.value)

        for (let i = 0; i < orderGoods.value.length; i++){
          const params = {
            id: orderGoods.value[i].prod_id,
            count: orderGoods.value[i].count
          };
          await ProductApi.updateStore(params)
        }
        router.push('/cart');
      })
      .catch(() => {
        // 用户点击“取消”，不执行操作（可加提示）
        ElMessage.info('已取消支付');
      });
};
</script>

<style scoped>
/* 支付确认弹窗：地址信息样式 */
.address-detail {
  display: flex;
  flex-direction: column;
  gap: 4px; /* 姓名电话与地址之间的间距 */
}

.address-receiver {
  font-weight: 500;
  color: #333;
}

.address-content {
  color: #666;
  word-break: break-all; /* 长地址自动换行 */
  margin-top: 2px;
}

/* 商品明细优化：增加间距，突出名称 */
.product-info strong {
  color: #333;
  font-size: 14px;
}

.product-item {
  padding: 8px 0; /* 增加商品项上下间距 */
}
/* 基础样式 */
.payment-page {
  min-height: 100vh;
  background-color: #f5f5f5;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
  padding-bottom: 80px; /* 给底部支付栏留空间 */
}

/* 加载状态 */
.cart-loading {
  text-align: center;
  padding: 80px 0;
  color: #666;
}

.loading-spinner {
  width: 40px;
  height: 40px;
  margin: 0 auto 16px;
  border: 4px solid #f3f3f3;
  border-top: 4px solid #ff5722;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

/* 订单错误提示 */
.order-error {
  background-color: #fff8f8;
  border: 1px solid #ffebe6;
  border-radius: 8px;
  padding: 40px 20px;
  text-align: center;
  margin-bottom: 20px;
}

.error-icon {
  color: #ff5722;
  font-size: 24px;
  margin-bottom: 12px;
}

.error-text {
  color: #ff4d4f;
  font-size: 14px;
  margin-bottom: 20px;
}

.go-cart-btn {
  padding: 8px 20px;
  background-color: #ff5722;
  color: #fff;
  border: none;
  border-radius: 4px;
  font-size: 14px;
  cursor: pointer;
  transition: background-color 0.2s;
}

.go-cart-btn:hover {
  background-color: #e64a19;
}

/* 地址管理模块 */
.address-card {
  background-color: #fff;
  border-radius: 8px;
  padding: 15px;
  margin-bottom: 15px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.02);
  cursor: pointer;
  transition: box-shadow 0.2s;
}

.address-card:hover {
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.05);
}

.address-content {
  padding: 5px 0;
}

.recipient-info {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
  font-size: 14px;
  color: #333;
  flex-wrap: wrap; /* 小屏幕换行 */
}

.recipient-name {
  margin-right: 15px;
  font-weight: 500;
}

.recipient-phone {
  color: #666;
}

.address-detail {
  font-size: 14px;
  color: #666;
  line-height: 1.5;
  word-break: break-all; /* 长地址换行 */
}

.address-placeholder {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 30px 0;
  color: #999;
  font-size: 14px;
}

.add-icon {
  margin-right: 8px;
  color: #ff5722;
}

/* 地址弹窗样式 */
.address-list {
  max-height: 400px;
  overflow-y: auto;
  padding: 10px 0;
}

.dialog-address-item {
  padding: 12px 0;
  border-bottom: 1px solid #f5f5f5;
  cursor: pointer;
  position: relative;
  padding-right: 120px;
  transition: background-color 0.2s;
}

.dialog-address-item:hover {
  background-color: #fafafa;
}

.addr-recipient {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
  font-size: 14px;
  flex-wrap: wrap;
}

.addr-name {
  margin-right: 15px;
  font-weight: 500;
  color: #333;
}

.addr-phone {
  color: #666;
  margin-right: 10px;
}

.addr-detail {
  font-size: 14px;
  color: #666;
  line-height: 1.5;
  margin-bottom: 8px;
  word-break: break-all;
}

.addr-actions {
  position: absolute;
  right: 0;
  top: 50%;
  transform: translateY(-50%);
  display: flex;
  gap: 10px;
}

.addr-edit, .addr-delete {
  border: none;
  background: transparent;
  font-size: 12px;
  padding: 4px 8px;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.2s;
}

.addr-edit {
  color: #409eff;
}

.addr-edit:hover {
  background-color: #ecf5ff;
}

.addr-delete {
  color: #f56c6c;
}

.addr-delete:hover {
  background-color: #fef0f0;
}

.add-address-btn {
  width: 100%;
  height: 44px;
  margin-top: 15px;
  border: 1px dashed #ff5722;
  background-color: #fff8f8;
  color: #ff5722;
  border-radius: 4px;
  font-size: 14px;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.2s;
}

.add-address-btn:hover {
  background-color: #fff0e8;
  border-style: solid;
}

.address-form {
  margin-top: 10px;
}

/* 头部样式 */
.payment-header {
  display: flex;
  align-items: center;
  padding: 16px 20px;
  background-color: #fff;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
  position: sticky;
  top: 0;
  z-index: 100; /* 避免被遮挡 */
}

.back-btn {
  border: none;
  background: transparent;
  font-size: 18px;
  color: #333;
  cursor: pointer;
  padding: 4px 8px;
  display: flex;
  align-items: center;
  transition: color 0.2s;
}

.back-btn:hover {
  color: #ff5722;
}

.page-title {
  font-size: 18px;
  font-weight: 500;
  color: #333;
  margin: 0 auto;
}

/* 主体内容 */
.payment-content {
  max-width: 1200px;
  margin: 0 auto;
  padding: 15px;
  box-sizing: border-box;
}

/* 支付方式卡片 */
.payment-method-card {
  background-color: #fff;
  border-radius: 8px;
  padding: 15px;
  margin-bottom: 15px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.02);
}

.card-header {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
}

.card-title {
  font-size: 16px;
  font-weight: 500;
  color: #333;
}

.item-total {
  margin-left: auto;
  font-size: 14px;
  color: #666;
}

.method-list {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.method-item {
  display: flex;
  align-items: center;
  padding: 12px;
  border: 1px solid #eee;
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.2s;
}

.method-item:hover {
  border-color: #ff5722;
  background-color: #fff8f8;
}

/* 选中支付方式样式 */
.method-item:has(.el-radio__input.is-checked) {
  border-color: #ff5722;
  background-color: #fff8f8;
}

.method-icon {
  width: 40px;
  height: 40px;
  margin-right: 12px;
  flex-shrink: 0;
}

.icon-img {
  width: 100%;
  height: 100%;
  object-fit: contain;
}

.method-name {
  font-size: 15px;
  color: #333;
  font-weight: 500;
  margin-right: 8px;
}

.method-desc {
  font-size: 12px;
  color: #999;
  margin-right: auto;
}

.method-selector {
  margin-left: 10px;
}

/* 订单明细卡片 */
.order-detail-card {
  background-color: #fff;
  border-radius: 8px;
  padding: 15px;
  margin-bottom: 15px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.02);
}

.detail-list {
  max-height: 250px;
  overflow-y: auto;
  margin-bottom: 15px;
  /* 滚动条美化 */
  &::-webkit-scrollbar {
    width: 6px;
  }
  &::-webkit-scrollbar-thumb {
    background-color: #eee;
    border-radius: 3px;
  }
}

.detail-item {
  display: flex;
  align-items: flex-start;
  padding: 12px 0;
  border-bottom: 1px solid #f5f5f5;
}

.item-img {
  width: 60px;
  height: 60px;
  border-radius: 4px;
  overflow: hidden;
  margin-right: 12px;
  flex-shrink: 0;
  margin-top: 2px;
  border: 1px solid #f5f5f5;
}

.goods-img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: opacity 0.3s;
}

.goods-img:hover {
  opacity: 0.9;
}

.item-info {
  flex: 1;
  min-width: 0;
}

.item-name {
  font-size: 14px;
  color: #333;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  margin-bottom: 6px;
}

.item-price-row {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.item-unit-price {
  font-size: 13px;
  color: #666;
  text-decoration: line-through;
}

.item-subtotal {
  font-size: 14px;
  color: #333;
  font-weight: 500;
}

.item-quantity {
  font-size: 14px;
  color: #666;
  margin-left: auto;
  margin-top: 2px;
}

.order-total {
  margin-top: 10px;
}

.total-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 9px 0;
  font-size: 14px;
  border-bottom: 1px solid #f5f5f5;
}

.total-label {
  color: #666;
}

.total-value {
  color: #333;
}

.discount {
  color: #ff4d4f;
  display: flex;
  align-items: center;
}

.discount-icon {
  margin-left: 8px;
  cursor: pointer;
  transition: color 0.2s;
}

.discount-icon:hover {
  color: #f5222d;
}

.final-total {
  border-bottom: none;
  margin-top: 5px;
  padding-top: 10px;
}

.final-total .total-label {
  font-size: 16px;
  font-weight: 500;
  color: #333;
}

.final-total .total-value {
  font-size: 18px;
  font-weight: 500;
  color: #ff5722;
}

/* 底部支付栏 */
.payment-footer {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 12px 20px;
  background-color: #fff;
  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.05);
  z-index: 100;
}

.footer-left {
  display: flex;
  flex-direction: column;
}

.footer-total {
  display: flex;
  align-items: center;
}

.total-text {
  font-size: 16px;
  color: #333;
  margin-right: 8px;
}

.total-amount {
  font-size: 20px;
  font-weight: 500;
  color: #ff5722;
}

.pay-btn {
  width: 180px;
  height: 44px;
  background-color: #ff5722;
  color: #fff;
  border: none;
  border-radius: 22px;
  font-size: 16px;
  font-weight: 500;
  cursor: pointer;
  transition: background-color 0.2s;
  display: flex;
  align-items: center;
  justify-content: center;
}

.pay-btn:hover {
  background-color: #e64a19;
}

.pay-btn:disabled {
  background-color: #ffb899;
  cursor: not-allowed;
}

.pay-loading {
  width: 20px;
  height: 20px;
}

/* 优惠明细弹窗样式 */
.discount-detail-list {
  padding: 10px 0;
}

.discount-detail-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 10px 0;
  font-size: 14px;
  border-bottom: 1px solid #f5f5f5;
}

.discount-detail-item:last-child {
  border-bottom: none;
}

.discount-type {
  color: #333;
}

.discount-amount {
  color: #ff4d4f;
  font-weight: 500;
}

.discount-note {
  margin-top: 15px;
  padding-top: 10px;
  border-top: 1px dashed #eee;
  font-size: 12px;
  color: #999;
  display: flex;
  align-items: center;
}

.note-icon {
  color: #ff9800;
  margin-right: 8px;
}

/* 支付确认弹窗样式（新增：商品明细样式） */
.pay-confirm-content {
  padding: 10px 0;
}

.confirm-item {
  display: flex;
  align-items: flex-start;
  padding: 12px 0;
  border-bottom: 1px solid #f5f5f5;
  font-size: 14px;
}

.confirm-item:last-child {
  border-bottom: none;
}

.confirm-label {
  width: 80px;
  color: #666;
  flex-shrink: 0;
  padding-top: 2px;
}

.confirm-value {
  color: #333;
  flex: 1;
}

.confirm-value.amount {
  color: #ff5722;
  font-weight: 500;
  font-size: 16px;
}

.confirm-item .copy-btn {
  margin-left: 10px;
  font-size: 12px;
}

/* 商品明细样式 */
.product-details {
  flex-direction: column;
  align-items: flex-start;
}

.product-list {
  width: 100%;
  margin-left: 80px;
  margin-top: 5px;
}

.product-item {
  padding: 5px 0;
  font-size: 13px;
  color: #666;
  border-bottom: 1px dashed #f0f0f0;
}

.product-item:last-child {
  border-bottom: none;
}

.product-info {
  display: block;
  word-break: break-all;
}

/* 响应式适配 */
@media (max-width: 768px) {
  .payment-content {
    padding: 10px;
  }

  .method-name {
    font-size: 14px;
  }

  .method-desc {
    display: none;
  }

  .item-unit-price {
    display: none;
  }

  .footer-left {
    flex: 1;
  }

  .pay-btn {
    width: 140px;
    height: 40px;
    font-size: 14px;
  }

  .total-amount {
    font-size: 18px;
  }

  /* 小屏幕地址操作按钮换行 */
  .addr-actions {
    position: static;
    transform: none;
    margin-top: 8px;
  }

  .dialog-address-item {
    padding-right: 0;
  }

  /* 弹窗商品明细适配 */
  .product-list {
    margin-left: 0;
    margin-top: 8px;
  }

  .confirm-label {
    width: 70px;
  }
}

@media (max-width: 480px) {
  .page-title {
    font-size: 16px;
  }

  .item-img {
    width: 50px;
    height: 50px;
  }

  .item-name {
    font-size: 13px;
  }

  .final-total .total-label,
  .final-total .total-value {
    font-size: 16px;
  }

  .pay-btn {
    width: 120px;
  }
}
</style>
